#include "uentity.h"

//UScene methods implementation

UScene::UScene(IChangeManager* pUSceneCM, IChangeManager* pUObjectCM)
{

}

//UObject methods implementation

UObject::UObject(u32 id)
{
    _id = id;
}

void UObject::subscribeForEvents( IEventSubscriber* subscriber, i32 eventType )
{
	_subscribers[eventType].insert(subscriber);
}

void UObject::unsubscribeFromEvents( IEventSubscriber* subscriber, i32 eventType )
{
	_subscribers[eventType].erase(subscriber);
}

void UObject::notifySubscribers( i32 eventType )
{
	set<IEventSubscriber*>::iterator it = _subscribers[eventType].begin();
	for ( ; it != _subscribers[eventType].end(); ++it)
	{
		(*it)->receiveEvent(eventType);
	}
}

PSystemObject UObject::extend( PSystemScene scene, SettingsMap& settings )
{
	if(scene == NULL)
		return NULL;
	PSystemObject sysobj = scene->CreateSystemObject(settings);
	if(sysobj != NULL)
	{
		_extensions[scene->GetSystemType()].insert(sysobj);
		Log(blue,"UObject #%u was extended with system object #%u from %s scene!", _id, sysobj->GetID(), scene->GetSystem()->GetName());
	} else 
		Log(red,"UObject #%u wasn't successfully extended from %s scene!", _id, scene->GetSystem()->GetName());
	// TODO: Add subscription for events to system object
	return sysobj;
}

Error UObject::extend( PSystemObject object )
{
	if(object == NULL) 
	{
		Log(red,"UObject #%u wasn't successfully extended!", _id);
		return Error::Null_ptr;
	}
	_extensions[object->GetSystemType()].insert(object);
	Log(blue,"UObject #%u was extended with system object #%u from %s scene!", _id, object->GetID(), object->GetSystemScene()->GetSystem()->GetName());
	// TODO: Add subscription for events to system object
	return Error::Success;
}

Error UObject::unExtend( PSystemObject object )
{
	if (object == NULL)
	{
		Log(red,"UObject #%u wasn't successfully unextended!", _id);
		return Error::Null_ptr;
	}
	Error e = Error::Success;
	try
	{
		set<PSystemObject>::iterator it = _extensions[object->GetSystemType()].find(object);
		_extensions[object->GetSystemType()].erase(it);
		// TODO: Add unsubscription for events to system object
	}
	catch (...)
	{
		e = Error::Not_found;
	}
	
	return e;
	
}

unsigned int UObject::getID()
{
	return _id;
}

void UObject::setID( u32 id )
{
	_id = id;
}
